package com.ymh.utils;


import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Created by aivin on 2018/7/26.
 * 使用JDBC连接数据库的工具类
 * 1、获取连接Connection
 * 2、释放资源
 */
public class JDBCUtil {

    /**
     * 获取连接Connection
     *
     * @return 所获取到的JDBC的Connection
     */
    public static Connection getConnection() throws Exception {

        /**
         * 不建议把配置硬编码到代码中
         *
         * 最佳实践：配置性的属性建议写到配置文件中
         */
//        String url = "jdbc:mysql://ssm";
//        String user = "root";
//        String password = "123456";
//        String driverClass = "com.mysql.jdbc.Driver";

        //从配置文件中获取数据
        InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        String url = properties.getProperty("jdbc.url");
        String user = properties.getProperty("jdbc.user");
        String password = properties.getProperty("jdbc.password");
        String driverClass = properties.getProperty("jdbc.driverClass");

        Class.forName(driverClass);
        Connection connection = (Connection) DriverManager.getConnection(url, user, password);
        return connection;
    }

    /**
     * 释放掉相应的资源
     *
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void release(ResultSet resultSet, Statement statement, Connection connection) {

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}
